package com.mc2.docapp.disabilityassessmenttool;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.mc2.docapp.disabilityassessmenttool.LowerLimb.Lower_Limb_Mobility_Component;
import com.mc2.docapp.disabilityassessmenttool.Misc.InputFilterMinMax;
import com.mc2.docapp.disabilityassessmenttool.UpperLimb.CustDataType;

import java.util.HashSet;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

import static com.mc2.docapp.disabilityassessmenttool.utils.Statics.getEditTexts;
import static com.mc2.docapp.disabilityassessmenttool.utils.Statics.router;


public class LowLimbMobilityComponent extends Activity {


    private static final int id = Activities.LOWER_LIMB_MOBILITY_COMPONENT;

    EditText walkingonPlainSurLeft;
    EditText walkingonPlainSurRight;
    EditText walkingonSlopeLeft;
    EditText walkingonSlopeRight;
    EditText climbingStairsLeft;
    EditText climbingStairsRight;
    EditText standingBothLegsLeft;
    EditText standingBothLegsRight;
    EditText standingOnAffectedLegLeft;
    EditText standingOnAffectedLegRight;
    EditText squattingLeft;
    EditText squattingRight;
    EditText sittingCrossLegLeft;
    EditText sittingCrossLegRight;
    EditText kneelingLeft;
    EditText kneelingRight;
    EditText takingTurnsLeft;
    EditText takingTurnsRight;

    public Lower_Limb_Mobility_Component lower_limb_mobility_component = new Lower_Limb_Mobility_Component();
    //db instance
    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_low_limb_mobility_component);
        walkingonPlainSurLeft      =(EditText) findViewById(R.id.walkingonPlainSurLeft);
        walkingonPlainSurRight     =(EditText) findViewById(R.id.walkingonPlainSurRight);
        walkingonSlopeLeft         =(EditText) findViewById(R.id.walkingonSlopeLeft);
        walkingonSlopeRight        =(EditText) findViewById(R.id.walkingonSlopeRight);
        climbingStairsLeft         =(EditText) findViewById(R.id.climbingStairsLeft);
        climbingStairsRight        =(EditText) findViewById(R.id.climbingStairsRight);
        standingBothLegsLeft       =(EditText) findViewById(R.id.standingBothLegsLeft);
        standingBothLegsRight      =(EditText) findViewById(R.id.standingBothLegsRight);
        standingOnAffectedLegLeft  =(EditText) findViewById(R.id.standingOnAffectedLegLeft);
        standingOnAffectedLegRight =(EditText) findViewById(R.id.standingOnAffectedLegRight);
        squattingLeft              =(EditText) findViewById(R.id.squattingLeft);
        squattingRight             =(EditText) findViewById(R.id.squattingRight);
        sittingCrossLegLeft        =(EditText) findViewById(R.id.sittingCrossLegLeft);
        sittingCrossLegRight       =(EditText) findViewById(R.id.sittingCrossLegRight);
        kneelingLeft               =(EditText) findViewById(R.id.kneelingLeft);
        kneelingRight              =(EditText) findViewById(R.id.kneelingRight);
        takingTurnsLeft			   =(EditText) findViewById(R.id.takingTurnsLeft);
        takingTurnsRight		   =(EditText) findViewById(R.id.takingTurnsRight);

        initRealmDB();
        loadPrevData();
        sanitizeInputs();

        Button saveNnextButton = (Button) findViewById(R.id.saveAndNext);
        saveNnextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                lower_limb_mobility_component.setWalkingPlainSurface(new CustDataType(Integer.parseInt(IfNull(walkingonPlainSurRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(walkingonPlainSurLeft.getText().toString(), "0")), 0d, 0, 0));

                lower_limb_mobility_component.setWalkingSlope(new CustDataType(Integer.parseInt(IfNull(walkingonSlopeRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(walkingonSlopeLeft.getText().toString(), "0")), 0d, 0, 0));

                lower_limb_mobility_component.setClimbingStairs(new CustDataType(Integer.parseInt(IfNull(climbingStairsRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(climbingStairsLeft.getText().toString(), "0")), 0d, 0, 0));

                lower_limb_mobility_component.setStandingBothLegs(new CustDataType(Integer.parseInt(IfNull(standingBothLegsRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(standingBothLegsLeft.getText().toString(), "0")), 0d, 0, 0));

                lower_limb_mobility_component.setStandingAffectedLeg(new CustDataType(Integer.parseInt(IfNull(standingOnAffectedLegRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(standingOnAffectedLegLeft.getText().toString(), "0")), 0d, 0, 0));

                lower_limb_mobility_component.setSquatting(new CustDataType(Integer.parseInt(IfNull(squattingRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(squattingLeft.getText().toString(), "0")), 0d, 0, 0));

                lower_limb_mobility_component.setSittingCrossLegged(new CustDataType(Integer.parseInt(IfNull(sittingCrossLegRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(sittingCrossLegLeft.getText().toString(), "0")), 0d, 0, 0));

                lower_limb_mobility_component.setKneeling(new CustDataType(Integer.parseInt(IfNull(kneelingRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(kneelingLeft.getText().toString(), "0")), 0d, 0, 0));

                lower_limb_mobility_component.setTakingTurns(new CustDataType(Integer.parseInt(IfNull(takingTurnsRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(takingTurnsLeft.getText().toString(), "0")), 0d, 0, 0));

                lower_limb_mobility_component.calc(lower_limb_mobility_component);

                NewPatient.finalDto.getClass_lowerLimb_component().setLower_limb_mobility_component(lower_limb_mobility_component);

                calculateCombMobStab(true);
                calculateCombMobStab(false);



                try {
//                    System.out.println(new ObjectMapper().writeValueAsString(c_active_rom));
                } catch (Exception e) {
                }
                System.out.println();
                lower_limb_mobility_component.setId(id);
                realm.beginTransaction();
                realm.deleteAll();
                realm.insert(lower_limb_mobility_component);
                realm.commitTransaction();

                Intent intent = new Intent(LowLimbMobilityComponent.this, router(LowLimbMobilityComponent.class));
                startActivity(intent);

            }
        });
        Button clearAll = (Button) findViewById(R.id.clear);
        clearAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashSet<EditText> views = new HashSet<>();
                getEditTexts((ViewGroup) findViewById(R.id.activity_main), views);
                for (EditText h : views)
                    h.setText("");
            }
        });


    }

    private void calculateCombMobStab(Boolean isLeft) {
        if(isLeft) {
            double a = NewPatient.finalDto.getClass_lowerLimb_component().getMobilityComponentLeft();
            double b = NewPatient.finalDto.getClass_lowerLimb_component().getLower_limb_mobility_component().getInner_calculations().getSummation_left();
            double combMobStabComp = calByFormula(a, b);

            if(combMobStabComp > 90) {
                combMobStabComp = 90d;
            }

            NewPatient.finalDto.getClass_lowerLimb_component().setCombMobStabCompLEFT(combMobStabComp);

        } else {

            double a = NewPatient.finalDto.getClass_lowerLimb_component().getMobilityComponentRight();
            double b = NewPatient.finalDto.getClass_lowerLimb_component().getLower_limb_mobility_component().getInner_calculations().getSummation_right();
            double combMobStabComp = calByFormula(a, b);

            if(combMobStabComp > 90) {
                combMobStabComp = 90d;
            }

            NewPatient.finalDto.getClass_lowerLimb_component().setCombMobStabCompRIGHT(combMobStabComp);


        }

    }
    private double calByFormula(double a, double b) {
        if(a<b){
            a = a + b;
            b = a - b;
            a = a - b;
        }
        double c = a + (((90 - a) * b) / 90.0);
        return c;
    }

    public void sanitizeInputs() {
        walkingonPlainSurLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        walkingonPlainSurRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        walkingonSlopeLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        walkingonSlopeRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        climbingStairsLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        climbingStairsRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        standingBothLegsLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        standingBothLegsRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        standingOnAffectedLegLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        standingOnAffectedLegRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        squattingLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        squattingRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        sittingCrossLegLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        sittingCrossLegRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        kneelingLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        kneelingRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        takingTurnsLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        takingTurnsRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
    }

    public String IfNull(String value, String defaultValue) {
        if(value == null || value.isEmpty()) {
            return defaultValue;
        } else {
            return  value;
        }
    }

    private void initRealmDB() {
        Realm.init(getApplicationContext());
        // realm = Realm.getDefaultInstance();
        RealmConfiguration config = new RealmConfiguration.Builder().name(id+".realm").build();
        realm = Realm.getInstance(config);
    }

    private void loadPrevData() {
        final RealmResults<Lower_Limb_Mobility_Component> dtos = realm.where(Lower_Limb_Mobility_Component.class).findAll();
//        .equalTo("id",id).findAll();
        System.out.println();
        try {
            //apply ui
            //
            //mapUI(new Lower_Limb_Mobility_Component().strip(dtos.get(0)));
            //
            //realm.beginTransaction();
            //dtos.get(0).deleteFromRealm();
            //realm.commitTransaction();
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
            //no prev data found
        }
    }

    private void mapUI(Lower_Limb_Mobility_Component oldData) {
        walkingonPlainSurLeft.setText(String.valueOf((long) (oldData.getWalkingPlainSurface().getActual_left())));
        walkingonPlainSurRight.setText(String.valueOf((long)(oldData.getWalkingPlainSurface()).getActual_right()));

        walkingonSlopeLeft.setText(String.valueOf((long) (oldData.getWalkingSlope().getActual_left())));
        walkingonSlopeRight.setText(String.valueOf((long) (oldData.getWalkingSlope().getActual_right())));

        climbingStairsLeft.setText(String.valueOf((long) (oldData.getClimbingStairs().getActual_left())));
        climbingStairsRight.setText(String.valueOf((long) (oldData.getClimbingStairs().getActual_right())));

        standingBothLegsLeft.setText(String.valueOf((long) (oldData.getStandingBothLegs().getActual_left())));
        standingBothLegsRight.setText(String.valueOf((long) (oldData.getStandingBothLegs().getActual_right())));

        standingOnAffectedLegLeft.setText(String.valueOf((long) (oldData.getStandingAffectedLeg().getActual_left())));
        standingOnAffectedLegRight.setText(String.valueOf((long) (oldData.getStandingAffectedLeg().getActual_right())));

        squattingLeft.setText(String.valueOf((long) (oldData.getSquatting().getActual_left())));
        squattingRight.setText(String.valueOf((long) (oldData.getSquatting().getActual_right())));

        sittingCrossLegLeft.setText(String.valueOf((long) (oldData.getSittingCrossLegged().getActual_left())));
        sittingCrossLegRight.setText(String.valueOf((long) (oldData.getSittingCrossLegged().getActual_right())));

        kneelingLeft.setText(String.valueOf((long) (oldData.getKneeling().getActual_left())));
        kneelingRight.setText(String.valueOf((long) (oldData.getKneeling().getActual_right())));

        takingTurnsLeft.setText(String.valueOf((long) (oldData.getTakingTurns().getActual_left())));
        takingTurnsRight.setText(String.valueOf((long) (oldData.getTakingTurns().getActual_right())));

    }
}
